/*
 * Ambiente.h
 *
 *  Created on: 25-10-2011
 *      Author: cristian
 */

#ifndef AMBIENTE_H_
#define AMBIENTE_H_

#include "HalThread.h"
#include "Logger.h"
#include <map>

template<typename T> class Ambiente: public HalThread {

private:
	Logger* logger;

protected:
	std::map<unsigned int, map<unsigned int, T*>*>* ambiente2;

public:

	Ambiente();
	virtual ~Ambiente();
	void setNodo(unsigned int x, unsigned int y, T* nodo);
	T* getNodo(unsigned int x, unsigned int y);
	unsigned int sizeMat();
	std::map<unsigned int, map<unsigned int, T*> *> *getAmbiente2() const;
	void deleteWorker(unsigned int x, unsigned int y);
};

template<typename T> Ambiente<T>::Ambiente() {

	logger = new Logger();
	this->ambiente2 = new std::map<unsigned int, map<unsigned int, T*>*>;

}

template<typename T> Ambiente<T>::~Ambiente() {
	delete logger;
	delete this->ambiente2;
}

template<typename T> void Ambiente<T>::setNodo(unsigned int x, unsigned int y, T *nodo) {

	typename map<unsigned int, map<unsigned int, T*>*>::iterator iterx = this->ambiente2->begin();

	iterx = this->ambiente2->find(x);

	if (iterx != this->ambiente2->end()) {

		map<unsigned int, T*>* nodemap = iterx->second;

		if (nodemap != NULL) {
			nodemap->insert(pair<unsigned int, T*>(y, nodo));
		} else {
#ifdef TRACE
			HAL_TRACE_CORE(logger, " Error fila worker (%i,%i) Nula ", x, y);
#endif
		}

	} else {
		std::map<unsigned int, T*>* nodospace = new std::map<unsigned int, T*>;
		nodospace->insert(pair<unsigned int, T*>(y, nodo));
		this->ambiente2->insert(pair<unsigned int, map<unsigned int, T*>*>(x, nodospace));
	}
}

template<typename T> T *Ambiente<T>::getNodo(unsigned int x, unsigned int y) {

	typename map<unsigned int, map<unsigned int, T*>*>::iterator iterx = this->ambiente2->begin();

	iterx = this->ambiente2->find(x);

	if (iterx != this->ambiente2->end()) {

		map<unsigned int, T*>* nodemap = iterx->second;

		if (nodemap != NULL) {
			typename map<unsigned int, T*>::iterator itery = nodemap->begin();
			itery = nodemap->find(y);
			if (itery != nodemap->end()) {
				T* nodo = itery->second;
				return nodo;
			}

		}
	}
	return NULL;

}

template<typename T> inline std::map<unsigned int, map<unsigned int, T*> *> *Ambiente<T>::getAmbiente2() const {
	return this->ambiente2;
}

template<typename T> inline unsigned int Ambiente<T>::sizeMat() {
	return this->ambiente2->size;
}

template<typename T> inline void Ambiente<T>::deleteWorker(unsigned int x, unsigned int y) {
	typename map<unsigned int, map<unsigned int, T*>*>::iterator iterx = this->ambiente2->begin();

	iterx = this->ambiente2->find(x);

	if (iterx != this->ambiente2->end()) {

		map<unsigned int, T*>* nodemap = iterx->second;

		if (nodemap != NULL) {
			typename map<unsigned int, T*>::iterator itery = nodemap->begin();
			itery = nodemap->find(y);
			if (itery != nodemap->end()) {
				nodemap->erase(itery);
			}
		}
	}
}

#endif /* AMBIENTE_H_ */
